#include"Lock.hpp"

using namespace LockModule;

int ticket=100;


Mutex mt;


void* funct(void* arg)
{
    char* st=(char*)arg;
   while(1)
   {
    LockGuard  my_lock(mt);
    if(ticket>0)
    {
        //锁的位置不能放到这里，出现问题是因为在if判断时因为判断出错访问呢临界区
        //锁要加在最开始访问临界区的地方，要在if之前就加锁
        //pthread_mutex_lock(&plock);
        usleep(1000);
        printf("%s sell ticket: %d\n",st,ticket);
        ticket--;
    }
    else{
        break;
    }
   }
   return nullptr;
}

int main()
{
    pthread_t t1,t2,t3,t4;
    pthread_create(&t1,NULL,funct,(void*)"thread 1");
    pthread_create(&t2,NULL,funct,(void*)"thread 2");
    pthread_create(&t3,NULL,funct,(void*)"thread 3");
    pthread_create(&t4,NULL,funct,(void*)"thread 4");

    pthread_join(t1,NULL);
    pthread_join(t2,NULL);
    pthread_join(t3,NULL);
    pthread_join(t4,NULL);

    return 0;
}